package com.cloud.point.concurrent.general;

import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * synchronized 方法使用
 *
 * @author 24373
 * @version 1.0
 * @date 2024-06-14 11:28
 */
@Slf4j
public class TestSynchronized {

    public static void main(String[] args) {
        //test1();
        test2();

    }

    /**
     * 非静态方法锁调用对象this；
     * 单个对象调用不同的非静态方法，出现互斥；
     * 多个对象调用不同的非静态方法，不会互斥；是并行
     */
    private static void test1() {
        Sync s1 = new Sync();
        Thread t1 = new Thread(() -> s1.m1());
        Thread t2 = new Thread(() -> s1.m2());
        t1.start();
        t2.start();
    }

    /**
     * 静态方法锁类；
     * 单个对象、多个对象调用不同的静态方法，出现互斥；
     */
    private static void test2() {
        Sync s1 = new Sync();
        Sync s2 = new Sync();
        Thread t1 = new Thread(() -> s1.m3());
        Thread t2 = new Thread(() -> s2.m4());
        t1.start();
        t2.start();
    }

    static class Sync {
        public synchronized void m1() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("m1");
        }

        public synchronized void m2() {
            log.info("m2");
        }

        public static synchronized void m3() {
            log.info("m3");
        }

        public static synchronized void m4() {
            log.info("m4");
        }

    }

}

